//
//  Date+Extension.swift
//  Weibo
//
//  Created by Albert Zhu on 16/10/30.
//  Copyright © 2016年 Albert Zhu. All rights reserved.
//

import UIKit

private let dateFormatter = DateFormatter()
private let calendar = Calendar.current

extension Date {
    /// 计算与当前时间相差delta秒的日期字符串
    /// Date是结构体，给结构体添加'类'方法，不用class，用static修饰
    static func az_dateString(delta: TimeInterval) -> String {
        
        let date = Date(timeIntervalSinceNow: delta)
        
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        
        return dateFormatter.string(from: date)
    }
    
    /// 将新浪格式字符串转换成日期
    ///
    /// - parameter string:
    ///
    /// - returns:
    static func az_sinaDate(withString string: String) -> Date? {
        
        dateFormatter.locale = Locale(identifier: "en_US")
        dateFormatter.dateFormat = "EEE MMM d HH:mm:ss Z yyyy"
        
        let date = dateFormatter.date(from: string)
        
        return date
    }
    
    var az_dateDescription: String {
        
        if calendar.isDateInToday(self) {
            let delta = -Int(self.timeIntervalSinceNow)
            if delta < 60 {return "刚刚"}
            if delta < 3600 {return "\(delta / 60)分钟前"}
            
            return "\(delta / 3600)小时前"
        }
        
        var fmt = " HH:mm"
        
        if calendar.isDateInYesterday(self) {
            fmt = "昨天" + fmt
        }else{
            
            fmt = "MM-dd" + fmt
            
            let year = calendar.component(.year, from: self)
            let thisYear = calendar.component(.year, from: Date())
            
            if year != thisYear {
                fmt = "yyyy-" + fmt
            }
        }
        
        dateFormatter.dateFormat = fmt
        
        return dateFormatter.string(from: self)
    }
    
    var dateColor: UIColor {
        let delta = -Int(self.timeIntervalSinceNow)
        
        let color = delta / 3600 < 4 ? UIColor.az_RGBColor(red: 255, green: 108, blue: 0) : UIColor.az_RGBColor(red: 130, green: 130, blue: 130)
        
        return color
    }
}
